<!--
 * @name: 
 * @Author: JiaYing
 * @LastEditors: JiaYing
 * @Date: 2022-08-30 17:53:26
 * @LastEditTime: 2022-08-31 14:02:54
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" id="input1" placeholder="throttle" />
    <input type="text" id="input2" placeholder="debounce" />
  </body>
</html>

<script>
  function throttle(cb, wait = 300) {
    let timer = null;
    let prev = 0;
    return function () {
      let that = this;
      let agrs = arguments;
      let now = Date.now();
      let time = wait - (now - prev);
      if (time <= 0 || time > wait) {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        prev = now;
        cb.apply(that, agrs);
      } else {
        if (timer) return;
        timer = setTimeout(function () {
          cb.apply(that, agrs);
          timer = null;
          prev = now;
        }, time);
      }
    };
  }
  document.querySelector("#input1").addEventListener(
    "input",
    throttle(function (e) {
      console.log(this, e);
    }, 1000)
  );

  function debounce(cb, wait = 300) {
    let timer = null;
    let prev = 0;
    return function () {
      let that = this;
      let agrs = arguments;
      let now = Date.now();
      let time = wait - (now - prev);
      if (time <= 0 || time > wait) {
        if (timer) return;
        prev = now;
        cb.apply(that, agrs);
        clearTimeout(timer);
        timer = null;
      } else {
        if (timer) {
          clearTimeout(timer);
          prev = now;
        }
        timer = setTimeout(() => {
          cb.apply(that, agrs);
          timer = null;
          prev = now;
        }, time);
      }
    };
  }
  document.querySelector("#input2").addEventListener(
    "input",
    debounce(function (e) {
      console.log(this, e);
    }, 1000)
  );
</script>
